package com.onluy.plugins.nfc;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.util.Date;

public class NfcbReceiver extends BroadcastReceiver {
    TelephonyManager tm =null;
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("===========", "action:" + intent.getAction());
        //如果是去电
        if(intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)){
            String outNumber= intent .getStringExtra(Intent.EXTRA_PHONE_NUMBER);
            CellMan.getInstance().setOutNumber(outNumber);
            Log.e("===========", "call OUT:" + outNumber);
        }else{
            if(tm==null) {
                tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
                tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
                Log.e("===========", "init TelephonyManager listener" );
            }
        }
    }
    PhoneStateListener listener=new PhoneStateListener(){
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            //注意，方法必须写在super方法后面，否则incomingNumber无法获取到值。
            String outNumber=CellMan.getInstance().getOutNumber();
            super.onCallStateChanged(state, incomingNumber);
            switch(state){
                case TelephonyManager.CALL_STATE_IDLE:
                    Log.e("===========", "挂断:"+incomingNumber+"-"+outNumber );
                    //if(incomingNumber!=null && incomingNumber.equals( outNumber)){
                        CellMan.getInstance().setEndDate(new Date());
                        CellMan.getInstance().SendCallBackMsg();
                    CellMan.getInstance().setReceiver(incomingNumber);
                   // }
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    Log.e("===========", "通话中:"+incomingNumber+"-"+outNumber );
                    //if(incomingNumber!=null && incomingNumber.equals( outNumber)){
                       // Log.e("===========", "CellMan-setStartDate:" +incomingNumber+","+new Date().toString());
                        CellMan.getInstance().setStartDate(new Date());
                    //}
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    Log.e("===========", "响铃:来电号码:" +1+incomingNumber);
                    CellMan.getInstance().setOutNumber(incomingNumber);
                    break;
            }
        }
    };
}
